<!-- 适用于小程序特殊的透明获取手机号按钮 -->

<script lang="ts" setup>
import { userApi } from '@/request/api'
import { useProfile } from '@/stores'
import { useConsole, useHideLoading, useLoading } from '@/utils'
import { to } from 'await-to-js'

const emit = defineEmits(['done'])

const profile = useProfile()

// 支付宝小程序
// #ifdef MP-ALIPAY
async function onAlipayGetPhoneNumber(e: any) {
  useConsole?.log('onAlipayGetPhoneNumber', e)

  my.getPhoneNumber({
    fail: (getPhoneNumberErr: any) => {
      useConsole?.log('getPhoneNumber:fail', getPhoneNumberErr)
    },
    success: async (getPhoneNumberRes: any) => {
      useConsole?.log('getPhoneNumber:success', getPhoneNumberRes)

      useLoading(true)
      const [err, res] = await to(userApi.setPhoneNum({ encryptedData: getPhoneNumberRes.response }))
      useHideLoading()
      if (err) {
        return
      }

      profile.updateItems({
        phone: Number.parseInt(res),
      })

      emit('done')
    },
  })
}

async function onAlipayGetAuthorizeError(err: any) {
  useConsole?.log('onAlipayGetAuthorize:Error', err)
}
// #endif

// 微信小程序
// #ifdef MP-WEIXIN
async function onWechatGetPhoneNumber(e: any) {
  useConsole?.log(e)
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    return
  }

  useLoading(true)
  const [err, res] = await to(
    userApi.setPhoneNum({ code: e.detail.code }),
  )
  useHideLoading()
  if (err) {
    return
  }

  profile.updateItems({
    phone: Number.parseInt(res),
  })

  emit('done')
}
// #endif

// 快手小程序手机号
// #ifdef MP-KUAISHOU
async function onKuaiSohowPhone(e: any) {
  useLoading(true)
  ks.login({
    fail(loginErr: any) {
      useHideLoading()
    },
    async success(loginRes: any) {
      const [err, res] = await to(userApi.setPhoneNum({ encryptedData: e.detail.encryptedData, iv: e.detail.iv, code: loginRes.code }))
      useHideLoading()
      if (err) {
        return
      }
      profile.updateItems({
        phone: Number.parseInt(res),
      })
      emit('done')
    },
  })
}
// #endif
</script>

<template>
  <!-- #ifdef MP-WEIXIN -->
  <button
    class="absolute top-0 h-full w-full op-0"
    open-type="getPhoneNumber"
    @getphonenumber="onWechatGetPhoneNumber"
  ></button>
  <!-- #endif -->
  <!-- #ifdef MP-ALIPAY -->
  <button
    class="absolute top-0 h-full w-full op-0"
    open-type="getAuthorize"
    scope="phoneNumber"
    @getAuthorize="onAlipayGetPhoneNumber"
    @error="onAlipayGetAuthorizeError"
  ></button>
  <!-- #endif -->
  <!-- #ifdef MP-KUAISHOU -->
  <button
    class="absolute top-0 h-full w-full op-0"
    open-type="getPhoneNumber"
    @getphonenumber="onKuaiSohowPhone"
    @error="onAlipayGetAuthorizeError"
  ></button>
  <!-- #endif -->
</template>

<style lang="less" scoped></style>
